package com.coding.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

/**
 * @author Cynicism
 * @version 1.0
 * @project DyApp
 * @description
 * @date 2024/6/23 22:56:27
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private ChatEndpoint chatEndpoint;

    @Resource
    private HttpHandshakeInterceptor httpHandshakeInterceptor;

    /**
     * 注册WebSocket处理程序
     * @param registry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //将ChatEndpoint实例添加到处理程序映射中，与/chat/{userId}路径匹配
        registry.addHandler(chatEndpoint, "/chat/{userId}")
                .addInterceptors(httpHandshakeInterceptor)
                .setAllowedOrigins("*");//允许来自任何源的请求访问WebSocket。
    }
}
